﻿using System.Data;
using System.Data.SqlClient;

namespace EP.Base.BaseService.Manager.Dal.Helper
{
    public class SqlBulkCopyHelper
    {
        /// <summary>
        /// 批量写入数据
        /// </summary>
        /// <param name="connectionString">目标连接字符</param>
        /// <param name="tableName">目标表</param>
        /// <param name="dt">源数据</param>
        public static int SqlBulkCopyByDatatable(string connectionString, string tableName, DataTable dt)
        {
            //using (var conn = new SqlConnection(connectionString))
            //{
            using (var sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
            {
                sqlbulkcopy.DestinationTableName = tableName;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
                }
                sqlbulkcopy.WriteToServer(dt);
            }
            //}
            return 1;
        }
    }
}
